<template>
  <div>
    <el-drawer
      :title="title"
      :visible.sync="dialogEditer"
      :append-to-body="true"
      direction="rtl"
      custom-class="demo-drawer"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      ref="drawer"
    >
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm form"
        >
          <el-form-item label="企业名称" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入企业名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="企业网址">
            <el-input
              v-model="ruleForm.web_site"
              placeholder="请输入企业网址"
            ></el-input>
          </el-form-item>
          <el-form-item label="Email">
            <el-input
              v-model="ruleForm.email"
              placeholder="请输入Email"
            ></el-input>
          </el-form-item>
          <el-form-item label="行业类型">
            <el-select
              v-model="ruleForm.industry_id"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in industryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公司规模">
            <el-input
              v-model="ruleForm.scale"
              placeholder="请输入公司规模"
            ></el-input>
          </el-form-item>
          <el-form-item label="等级">
            <el-select
              v-model="ruleForm.level_id"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in customerLevelList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>

            <!-- <el-input
              v-model="ruleForm.level_id"
              placeholder="请输入等级"
            ></el-input> -->
          </el-form-item>
          <el-form-item label="地址">
            <div v-if="!mapShow" style="margin-bottom: 22px">
              <!-- 省 -->
              <el-select
                v-model="ruleForm.pid"
                filterable
                placeholder="请选择省"
                @change="getProvince(1, ruleForm.pid, 1)"
              >
                <el-option
                  v-for="item in provinceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <!-- 市 -->
              <el-select
                v-if="cityList.length !== 0"
                v-model="ruleForm.fid"
                filterable
                placeholder="请选择市"
                @change="getProvince(2, ruleForm.fid, 1)"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <!-- 区 -->
              <el-select
                v-if="areaList.length !== 0"
                v-model="ruleForm.area_id"
                filterable
                placeholder="请选择区"
                @change="areaChange($event)"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <el-input
              v-model="ruleForm.address"
              :placeholder="
                ruleForm.area_id == '' ? '请先选择省市区' : '请输入详细地址'
              "
            ></el-input>
            <div v-if="!mapShow" class="addressTips">
              <i class="el-icon-location-outline"></i>从地图中选择位置<span
                class="edit_btn"
                @click="mapCt"
                style="margin-left: 10px"
                >点击设置</span
              >
            </div>
            <div v-else class="addressTips">
              通过省市区进行地址选择
              <span
                class="edit_btn"
                @click="
                  mapShow = false;
                  ruleForm.address = '';
                "
                >点击设置</span
              >
            </div>
            <baidu-map
              v-loading="map_loading"
              v-if="mapShow"
              class="bm-view"
              ak="1A3jDbhjNcsCaBeNeUIaMfKnBDlDEMYi"
              :center="center"
              :zoom="zoom"
              @ready="onBaiduMapReady"
              :scroll-wheel-zoom="true"
              @click="getClickInfo"
            >
              <bm-view style="width: 100%; height: 300px"></bm-view>
              <bm-marker
                :position="{ lng: center.lng, lat: center.lat }"
                :dragging="true"
                animation="BMAP_ANIMATION_BOUNCE"
              >
                <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              </bm-marker>
              <bm-control :offset="{ width: '10px', height: '10px' }">
                <bm-auto-complete
                  v-model="keyword"
                  :sugStyle="{ zIndex: 999999 }"
                >
                  <input
                    type="text"
                    placeholder="请输入大致位置"
                    class="serachinput"
                  />
                </bm-auto-complete>
              </bm-control>
              <bm-local-search
                :keyword="keyword"
                :auto-viewport="true"
                style="width: 0px; height: 0px; overflow: hidden"
              ></bm-local-search>
            </baidu-map>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="ruleForm.remark"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="人员规模 ">
            <el-select v-model="ruleForm.number" placeholder="请选择来源">
              <el-option label="区域一" :value="0"></el-option>
              <el-option label="区域二" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="省市" prop="cities">
            <el-select v-model="ruleForm.cities" placeholder="请选择">
              <el-option label="区域一" :value="0"></el-option>
              <el-option label="区域二" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业等级">
            <el-select v-model="ruleForm.grade" placeholder="请选择">
              <el-option label="区域一" :value="0"></el-option>
              <el-option label="区域二" :value="1"></el-option>
            </el-select>
          </el-form-item> -->
        </el-form>
      </div>
      <div class="foot_btn" style="margin-bottom: 20px">
        <el-button @click="resetForm('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>


<script>
import { regionData, CodeToText } from "element-china-area-data";
import {
  BaiduMap,
  BmControl,
  BmView,
  BmAutoComplete,
  BmLocalSearch,
  BmMarker,
  BmNavigation,
} from "vue-baidu-map";
export default {
  components: {
    BaiduMap,
    BmControl,
    BmView,
    BmAutoComplete,
    BmLocalSearch,
    BmMarker,
    BmNavigation,
  },
  props: ["data", "start"],
  data() {
    return {
      // 是否显示弹出框
      dialogEditer: false,
      industryList: [], // 行业数据
      customerLevelList: [], // 等级数据
      // 弹出框标题
      title: "",
      provinceList: [],
      cityList: [],
      areaList: [],
      mapShow: false, //　地图是否展示
      map_loading: false,
      // 省市选择
      address: {
        province: "",
        city: "",
        area: "",
        details: "",
      },
      defaultSarat: true, // 地区默认状态-用于数据默认第一项以及清空地址
      //   表格内容
      ruleForm: {
        id: "",
        name: "",
        phone: "",
        web_site: "",
        email: "",
        industry_id: "",
        scale: "",
        level_id: "",
        pid: "",
        fid: "",
        area_id: "",
        address: "",
        detailed: "",
        remark: "",
        long: "",
        lat: "",
      },
      rules: {
        name: [{ required: true, message: "请输入企业全称", trigger: "blur" }],
      },
      center: { lng: 35.11067124, lat: 118.36353301 },
      zoom: 3,
      keyword: "",
      options: regionData,
    };
  },
  created() {
    this.getcustomerLevel();
    this.getIndustry();
  },
  watch: {
    dialogEditer(newData, oldData) {
      if (newData) {
        if (this.data && this.data.id) {
          this.title = "编辑企业";
          this.ruleForm = this.data;
          this.getProvince(0, "", 0);
          if (this.ruleForm.pid !== "") {
            this.getProvince(1, this.ruleForm.pid, 0);
            this.getProvince(2, this.ruleForm.fid, 0);
          }
        } else {
          this.title = "新增企业";
          this.ruleForm = this.$options.data().ruleForm;
          this.getProvince(0, "", 0);
        }
      }
    },
  },
  methods: {
    // 获取等级数据
    getcustomerLevel() {
      this.$cmsapi.customerLevelList().then(
        (res) => {
          if (res.code == 0) {
            this.customerLevelList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 获取行业数据
    getIndustry() {
      this.$cmsapi.labelLibraryList("ety3bHEAAAWD42yxQa8OuVd8PaocfpOw").then(
        (res) => {
          if (res.code == 0) {
            this.industryList = res.data[0].tag;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 省市区数据
    // type:级别
    // condition:参数
    // nothingness:是否为二次修改0否1是
    getProvince(type, condition, nothingness) {
      let that = this;
      this.$cmsapi.addressList(condition).then(
        (res) => {
          if (res.code == 0) {
            switch (type) {
              case 0:
                that.provinceList = res.data;
                if (that.ruleForm.pid == "") {
                  that.ruleForm.pid = res.data[0].id;
                  if (that.title == "新增企业" || this.ruleForm.long !== "") {
                    that.getProvince(1, res.data[0].id, 0);
                  }
                }
                if (nothingness == 1) {
                  that.getProvince(1, that.ruleForm.pid, 1);
                }
                break;
              case 1:
                that.cityList = res.data;
                if (that.ruleForm.fid == "" || nothingness == 1) {
                  that.ruleForm.fid = res.data[0].id;
                  if (that.title == "新增企业" || this.ruleForm.long !== "") {
                    that.getProvince(2, res.data[0].id, 0);
                  }
                }
                if (nothingness == 1) {
                  that.getProvince(2, that.ruleForm.fid, 1);
                }
                break;
              case 2:
                that.areaList = res.data;
                if (that.ruleForm.area_id == "" || nothingness == 1) {
                  that.ruleForm.area_id = res.data[0] ? res.data[0].id : "";
                }
                if (nothingness == 1) {
                  that.ruleForm.address = that.$options.data().ruleForm.address;
                }
                break;
              default:
                break;
            }
          } else {
            that.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 区数据监听
    areaChange(e) {
      this.ruleForm.address = this.$options.data().ruleForm.address;
    },
    mapCt() {
      this.ruleForm.pid = this.$options.data().ruleForm.pid;
      this.ruleForm.fid = this.$options.data().ruleForm.fid;
      this.ruleForm.area_id = this.$options.data().ruleForm.area_id;
      this.mapShow = true;
    },
    getClickInfo(e) {
      // 此时已经可以获取到BMap类
      if (this.BMap) {
        const that = this;
        // Geocoder() 类进行地址解析
        // 创建地址解析器的实例
        const geoCoder = new this.BMap.Geocoder();
        // getLocation() 类--利用坐标获取地址的详细信息
        // getPoint() 类--获取位置对应的坐标
        geoCoder.getLocation(e.point, function (res) {
          // console.log("获取经纬度", e.point, "获取详细地址", res);
          that.ruleForm.long = e.point.lng;
          that.ruleForm.lat = e.point.lat;

          const addrComponent = res.addressComponents;
          const surroundingPois = res.surroundingPois;
          const province = addrComponent.province;
          const city = addrComponent.city;
          const district = addrComponent.district;
          let addr = addrComponent.street;
          if (surroundingPois.length > 0 && surroundingPois[0].title) {
            if (addr) {
              addr += `-${surroundingPois[0].title}`;
            } else {
              addr += `${surroundingPois[0].title}`;
            }
          } else {
            addr += addrComponent.streetNumber;
          }
          that.ruleForm.address =
            province + "," + city + "," + district + "," + addr;
          that.choosedLocation = {
            province,
            city,
            district,
            addr,
            ...that.center,
          };
        });
      }
    },
    onBaiduMapReady(e) {
      this.map_loading = true;
      const that = this;
      this.BMap = e.BMap;
      if (this.BMap) {
        // 获取定位地址信息并赋值给声明变量
        // Geolocation 对象的 getCurrentPosition()、watchPosition()、clearWatch() 方法详解 ：https://blog.csdn.net/zyz00000000/article/details/82774543
        const geolocation = new this.BMap.Geolocation();
        // 通过 getCurrentPosition() 方法：获取当前的位置信息
        geolocation.getCurrentPosition((res) => {
          // console.log("返回详细地址和经纬度", res);
          const { lng, lat } = res.point;
          const { province, city, district, street, street_number } =
            res.address;
          that.center = {
            lat: lat,
            lng: lng,
          };
          that.ruleForm.long = lng;
          that.ruleForm.lat = lat;
          that.ruleForm.address = province + "," + city;
          that.choosedLocation = {
            province,
            city,
            district,
            addr: street + street_number,
            lng,
            lat,
          };
          that.map_loading = false;
        });
      }
    },
    // 提交
    submitForm(formName) {
      this.$emit.loading = true;
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.$cmsapi.customerSave(that.ruleForm).then(
            (res) => {
              if (res.code == 0) {
                that.$message({
                  type: "success",
                  message: that.ruleForm.id == "" ? "新增成功" : "编辑成功",
                });
                that.dialogEditer = false;
                that.ruleForm = this.$options.data().ruleForm;
                if (this.start == "0") {
                  // 如果是最后抽屉跳转对应模块刷新数据
                  this.$router.push({
                    path: "/customer/enterprise",
                    query: {
                      t: Date.now(),
                    },
                  });
                } else {
                  // 刷新上一层抽屉相关数据
                  this.$emit("getenterprise");
                }
                // that.$parent.getData();
              } else {
                that.$message.error(res.msg);
              }
              this.$emit.loading = false;
            },
            (err) => {
              console.log(err);
              that.$emit.loading = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置&取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogEditer = false;
      this.ruleForm = this.$options.data().ruleForm;
      // this.$router.go(0);
    },
  },
};
</script>
<style scoped>
.form {
  width: 95%;
}
.bm-view {
  width: 100%;
  height: auto;
}
.addressTips {
  font-size: 12px;
}
</style>